package com.my.framework.page;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import java.util.ArrayList;
import java.util.List;

public class PageUtils {

	/**
	 * 生成spring data JPA 对象 描述：单一字段排序
	 * 
	 * @param page
	 * @return
	 */
	public static Pageable createPageable(Page page) {
		if (StringUtils.isNotBlank(page.getOrderField())) {
			// 忽略大小写
			if (page.getOrderDirection().equalsIgnoreCase(Page.ORDER_DIRECTION_ASC)) {
				return new PageRequest(page.getPlainPageNum() - 1, page.getNumPerPage(),
						Sort.Direction.ASC, page.getOrderField());
			} else {
				return new PageRequest(page.getPlainPageNum() - 1, page.getNumPerPage(),
						Sort.Direction.DESC, page.getOrderField());
			}
		}
		return new PageRequest(page.getPlainPageNum() - 1, page.getNumPerPage());
	}
	/**
	 * 生成spring data JPA 对象：多字段排序
	 * 
	 * @param page
	 * @return
	 */
	public static Pageable createPageables(Page page) {
		if (page.getOrders()!=null) {
			List< Order> orders=new ArrayList< Order>();
			for (PageOrder order:page.getOrders()) {
				if (order.getOrderDirection().equalsIgnoreCase(Page.ORDER_DIRECTION_ASC)) {
					orders.add(new Order(Direction.ASC,order.getOrderField()));
				} else {
					orders.add(new Order(Direction.DESC, order.getOrderField()));
				}
			}
			return new PageRequest(page.getPlainPageNum() - 1, page.getNumPerPage(),new Sort(orders));
		}
		return new PageRequest(page.getPlainPageNum() - 1, page.getNumPerPage());
	}
	/**
	 * 将springDataPage的属性注入page描述
	 * 
	 * @param page
	 * @param springDataPage
	 */
	public static void injectPageProperties(Page page,
			org.springframework.data.domain.Page<?> springDataPage) {
		// 暂时只注入总记录数量
	    Long totalCount = 0L;
        if (null != springDataPage)
        {
            totalCount = springDataPage.getTotalElements();
        }
        page.setTotalCount(totalCount);
	}
}
